const express = require('express');
const router = express.Router();
const {searchCard,
    listCard,
    newCard,
    updateCard,
    deleteCard} = require('../controller/cards')
const {SuccessModel,ErrorModel} = require('../model/resModel')

// 借阅证信息列表
router.get('/list',function (req,res,next) {
    // 获取权限信息
    const role = req.query.role
    if(role>0){
        const result = listCard(role)
        return result.then(data => {
            res.json(new SuccessModel(data,200))
        })
    }else{
        res.json(401)
    }
    next()
})

// 查询借书证信息
router.get('/search',(req,res,next) =>{
    if(req.query.role<0){
        res.json(new ErrorModel(401))
    }else{
        // 获取要查询的信息
        const result = searchCard(req.query.role,req.query.type,req.query.input)
        return result.then(data => {
            // console.log(data)
            res.json( new SuccessModel(data,200))
        })
    }
    next()
})

// 新建借阅证
router.post('/new',(req,res,next) => {
    const {role,name,department,major,phone,limit,account} = req.body
    // console.log(role);
    if(role>0){
        const time = Date.now()
        const result = newCard(name,department,major,phone,limit,account,time)
        return result.then(data => {
            console.log(data)
            if(data.errno){
                res.json(new ErrorModel(422))
            }else{
                if(data.affectedRows>0){
                    res.json(new SuccessModel(data,200))
                    return
                }
                res.json(new ErrorModel(500))
            }
        })
    }
    next()
})

// 修改借阅证信息
router.post('/update',(req,res,next) => {
    const {role,id,type,input} = req.body
    if(role>=0){
        const result = updateCard(id,type,input)
        return result.then(data => {
            if(data.errno === 1){
                res.json(new ErrorModel(422))
            }else{
                if(data.affectedRows>0){
                    res.json(new SuccessModel(data,200))
                    return
                }
                res.json(new ErrorModel(500))
            }
        })
    }else{
        res.json(new ErrorModel(401))
    }
    next()
})

// 删除借阅证信息
router.post('/delete',(req,res,next) => {
    const {role,id} = req.body
    if(role < 2){
        if(role < 0){
            res.json(new ErrorModel(401))
        }
        res.json(new ErrorModel(403))
    }else{
        const result = deleteCard(id)
        return result.then(data => {
            if(data.errno){
                res.json(new ErrorModel(422))
            }else{
                if(data.affectedRows>0){
                    res.json(new SuccessModel(data,200))
                    return
                }
                res.json(new ErrorModel(500))
            }
        })
    }
    next()
})

module.exports = router;